package drone.basis.util ;

import java.util.Calendar ;
import java.util.Date ;
import java.util.HashMap ;
import java.util.Map ;

import com.auth0.jwt.JWT ;
import com.auth0.jwt.JWTCreator.Builder ;
import com.auth0.jwt.JWTVerifier ;
import com.auth0.jwt.algorithms.Algorithm ;
import com.auth0.jwt.interfaces.DecodedJWT ;

import drone.basis.GlobalConfig ;

public class JwtUtil
{

	private static Map < String , Object > jwtHeader = new HashMap < String , Object > ( ) ;

	static
	{
		jwtHeader.put ( "alg" , "HS256" ) ;
		jwtHeader.put ( "typ" , "JWT" ) ;
	}

	// 设定超时时间创建jwt令牌
	public static Builder create (Integer time)
	{
		Calendar now = Calendar.getInstance ( ) ;
		now.add ( Calendar.SECOND , time) ;
		Builder builder = JWT.create ( ) ;
		builder.withHeader ( jwtHeader ) ;
		builder.withIssuedAt ( new Date ( ) ) ;
		builder.withExpiresAt ( now.getTime ( ) ) ;
		return builder ;
	}

	// 获取签名
	public static String signature (
			Builder builder ,
			String sercet
	)
	{
		try
		{
			return builder.sign ( Algorithm.HMAC256 ( sercet ) ) ;
		} catch ( Exception e )
		{
			return null ;
		}

	}

	// 验证令牌是否有效
	public static boolean verify (
			String token ,
			String sercet
	)
	{
		try
		{
			JWT.require ( Algorithm.HMAC256 ( sercet ) ).build ( ).verify ( token ) ;
		} catch ( Exception e )
		{
			return false ;
		}
		return true ;
	}

	// 获取claims内的值
	public static String fetch (
			String token ,
			String sercet ,
			String key
	)
	{
		if ( ! verify ( token , sercet ) )
		{
			return null ;
		}
		JWTVerifier verifier = null ;
		DecodedJWT jwt = null ;
		try
		{
			verifier = JWT.require ( Algorithm.HMAC256 ( sercet ) ).build ( ) ;
			jwt = verifier.verify ( token ) ;
		} catch ( Exception e )
		{
			return null ;
		}
		return jwt.getClaims ( ).get ( key ).asString ( ) ;
	}

	// 获取claims内的值列表
	public static String [ ] array (
			String token ,
			String sercet ,
			String key
	)
	{
		if ( ! verify ( token , sercet ) )
		{
			return null ;
		}
		JWTVerifier verifier = null ;
		DecodedJWT jwt = null ;
		try
		{
			verifier = JWT.require ( Algorithm.HMAC256 ( sercet ) ).build ( ) ;
			jwt = verifier.verify ( token ) ;
		} catch ( Exception e )
		{
			return null ;
		}
		return jwt.getClaims ( ).get ( key ).asArray ( String.class ) ;
	}

	public static void main(String[] args) {
		String token = JwtUtil.signature ( JwtUtil.create ( GlobalConfig.JWTTIME ).withClaim ( "aaa" , "111" ) , GlobalConfig.JWTSECRET ) ;
		System.out.println(token);
		// 正常测试
		String asString = JwtUtil.fetch(token,GlobalConfig.JWTSECRET, "aaa");
		System.out.println(asString);

		String[] arr = JwtUtil.array(token,GlobalConfig.JWTSECRET, "item");
		for (String s : arr) {
			System.out.println(s);
		}

		boolean flag = JwtUtil.verify(token,GlobalConfig.JWTSECRET);
		System.out.println(flag);
	}
}
